package gui;

import java.awt.Dimension;
import java.awt.FlowLayout;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.JTableHeader;
import javax.swing.table.TableModel;
import server.TodoItem;

public class ContentMain extends JPanel{
    public static ContentMain instance = new ContentMain();
    
    private final String[] columnNames = {"Todo", "Deadline", "Last update","Priority"};
    private JScrollPane scrollPane;
    private DefaultTableModel tableModel ;
    private JTable table;
    private ArrayList<TodoItem> rowData ;
    
    private ContentMain(){
//        setLayout(new FlowLayout());
        Object[][] cellData = {};
        rowData = new ArrayList<TodoItem>();
        table = new JTable(){
            @Override
            public boolean isCellEditable(int row,int column){  
                return false;  
            }  
        };
        tableModel = new DefaultTableModel(cellData,columnNames);
        table.setModel(tableModel);
        table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
        table.getColumn("Last update").setMinWidth(100);
        scrollPane = new JScrollPane(table);
        scrollPane.setPreferredSize(new Dimension(700,490));
        this.add(scrollPane);
    }
    
    public void addRowTable(TodoItem item){
        String[] data = {item.getContent(),item.getDeadline(),item.getLasUpdate(), item.getPriority()+""};
//        System.out.println("item id="+item.getId());
        rowData.add(item);
        tableModel.addRow(data);
        
    }
    
    public void removeRowTable(int row){
        rowData.remove(row);
        tableModel.removeRow(row);
    }
    
    public void addNewTable(List<TodoItem> list){
        tableModel.getDataVector().removeAllElements();
        rowData = new ArrayList<TodoItem>();
        for(TodoItem item : list){
            addRowTable(item);
        }
        if(table.getRowCount()>0) table.setRowSelectionInterval(0, 0);
    }

    public JTable getTable(){
        return table;
    }
    
    public TodoItem getRowData(int index){
        return rowData.get(index);
    }
    
    public TodoItem getSelectedRowData(){
        if(table.getSelectedRow()>=0)
            return rowData.get(table.getSelectedRow());
        return null;
    }
}
